﻿import json

from utils.serialisator import *
from KA import super, KA
from jutils import *
from utilits import *

class GameManager(KA):
	def __init__(this):
		super.__init__(this)
		#// this.sendMsg("newGame");
	
	def _doRequest(this, req):
		if (not this.client):
			res = eval("this.pre_" + req.type)(req);
			if (res != null):
				ans = {};
				ans[ANS_VAL] = false;
				ans[ANS_TEXT] = res;
				return req.Answer(this, ans);
				
		eval("this." + req.type)(req);
		
		if (not this.client):
			res = eval("this.post_" + req.type)(req);
		
		ans = {};
		ans[ANS_VAL] = true;
		return req.Answer(this, ans);
	
	def doState(this, exitValue_):
		pass
	
	def exit(this):
		pass
	
	def stopGame(this):
		super.setState(this, GM_0);
	
	#// utilits 
	def sendMsg(this, msg):
		for usr in this.data.gamers:
			msg_to_send = {};
			msg_to_send[MSG_USR] = this.name;
			msg_to_send[MSG_TYPE] = "sendMsg";
			msg_body = {};
			msg_body["USER_NAME"] = usr;
			msg_body["MSG_BODY"] = msg;
			msg_to_send[MSG_BODY] = json.dumps(msg_body);
			this.bgtp_mail(msg_to_send);
	
	def sendRequest(this, req):
		msg = {};
		msg["USR"] = req.usr;
		msg["TYPE"] = req.type;
		msg["BODY"] = json.dumps(req.body)
		this.sendMsg(msg);
	
	#// interface for server
	def setSituation(this, situation_):
		situation = json.loads(situation_);
		this.state = situation["state"];
		
		#// этот кусок todo, т.к. наследник должен предоставлять список путей к классам
		importDictionary = {};
		importDictionary["XOdata"] = "games.XO.Rules.XOdata";
		
		this.data = deserialisator(situation["data"], importDictionary);
		
		#// этот кусок todo, т.к. надо тонче восстанавливать АИ, скорее всего переложить на наследников
		if (not this.client and this.data.partyes.values().count("AI") > 0):
			this.createAI(null);
		
		return true	
	
	def getSituation(this, forWhom):
		situation = {}
		situation["state"] = this.state
		situation["data"] = serialisator(this.data)
		return json.dumps(situation);

